package cn.hfatec.shms.web.td.tdHzb.service;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


import cn.hfatec.shms.cache.CodeInfoCache;
import cn.hfatec.shms.enums.CodeType;
import cn.hfatec.shms.system.codeInfo.model.CodeInfo;
import cn.hfatec.shms.web.members.ykBill.model.YkBill;
import cn.hfatec.shms.web.members.ykBill.model.YkBillParams;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.hfatec.base.BaseDao;
import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.shms.web.td.tdHzb.model.TdHzb;
import cn.hfatec.shms.web.td.tdHzb.dao.TdHzbDao;
import cn.hfatec.shms.web.td.tdHzb.model.TdHzbParams;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author hfatec
 * @version 1.0
 *          <p/>
 *          the JAVA code is generate by middlegen
 */
@Service("TdHzbService")
public class TdHzbService {

    public static final String BEAN_ID = "TdHzbService";

    //注入Dao层
    @Resource(name = "TdHzbDao")
    private TdHzbDao tdHzbDao;

    //注入BaseDao
    @Resource(name = "BaseDao")
    private BaseDao baseDao;

    @Transactional
    public static String encodeFilename(HttpServletRequest request, String fileName) {
        String rtn = "";
        try {
            String userAgent = request.getHeader("USER-AGENT");
            String new_filename = URLEncoder.encode(fileName, "UTF8");

            rtn = "filename=\"" + new_filename + "\"";

            if (userAgent != null) {
                userAgent = userAgent.toLowerCase();

                if (userAgent.indexOf("msie") != -1) {
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("opera") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                } else if (userAgent.indexOf("safari") != -1) {
                    rtn = "filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";
                } else if (userAgent.indexOf("applewebkit") != -1) {
                    new_filename = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("mozilla") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                }
            }
        } catch (UnsupportedEncodingException e) {
            try {
                rtn = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            } catch (UnsupportedEncodingException localUnsupportedEncodingException1) {
            }
        }
        return rtn;
    }

    /**
     * 查询数据
     *
     * @param tdHzbParams
     * @param page
     */
    @Transactional
    public Table queryTdHzbTable(TdHzbParams tdHzbParams, Page page) {

        HashMap<String, Object> params = new HashMap<String, Object>();
        String dateStart = null;
        if ((tdHzbParams.getbStart() == null) || (tdHzbParams.getbStart().isEmpty())) {
            Date dt = new Date();
            SimpleDateFormat matter1 = new SimpleDateFormat("yyyy-MM-dd");
            dateStart = matter1.format(dt);
        } else {
            dateStart = tdHzbParams.getbStart();
        }
        String bStart = null;
        String bEnd = null;
        String SStart = null;
        String SEnd = null;
        try {
            bStart = getFirstDay(dateStart);
            bEnd = getLastDay(dateStart);
            String sy = getSy(dateStart);
            SStart = getFirstDay(sy);
            SEnd = getLastDay(sy);

        } catch (Exception e) {
            e.printStackTrace();
        }
        tdHzbParams.setbStart(bStart);
        tdHzbParams.setbEnd(bEnd);
        tdHzbParams.setsStart(SStart);
        tdHzbParams.setsEnd(SEnd);
        params.put("params", tdHzbParams);
        return baseDao.queryTableByPage("queryTdHzb", params, page);
    }

    /**
     * 查询数据
     *
     * @param tdHzbParams
     */
    @Transactional
    public List queryTdHzbList(TdHzbParams tdHzbParams) {
        HashMap<String, Object> params = new HashMap<String, Object>();
        String dateStart = null;
        if ((tdHzbParams.getbStart() == null) || (tdHzbParams.getbStart().isEmpty())) {
            Date dt = new Date();
            SimpleDateFormat matter1 = new SimpleDateFormat("yyyy-MM-dd");
            dateStart = matter1.format(dt);
        } else {
            dateStart = tdHzbParams.getbStart();
        }
        String bStart = null;
        String bEnd = null;
        String SStart = null;
        String SEnd = null;
        try {
            bStart = getFirstDay(dateStart);
            bEnd = getLastDay(dateStart);
            String sy = getSy(dateStart);
            SStart = getFirstDay(sy);
            SEnd = getLastDay(sy);

        } catch (Exception e) {
            e.printStackTrace();
        }
        tdHzbParams.setbStart(bStart);
        tdHzbParams.setbEnd(bEnd);
        tdHzbParams.setsStart(SStart);
        tdHzbParams.setsEnd(SEnd);
        params.put("params", tdHzbParams);
        return baseDao.queryList("queryTdHzb", params);
    }

    public String getLastDay(String datadate) throws Exception {
        Date date = null;
        String day_last = null;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        date = format.parse(datadate);

        //创建日历
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, 1);    //加一个月
        calendar.set(Calendar.DATE, 1);     //设置为该月第一天
        calendar.add(Calendar.DATE, -1);    //再减一天即为上个月最后一天
        day_last = format.format(calendar.getTime());
        return day_last;
    }

    public String getFirstDay(String datadate) throws Exception {
        Date date = null;
        String day_first = null;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        date = format.parse(datadate);

        //创建日历
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        day_first = format.format(calendar.getTime());
        return day_first;
    }

    public String getSy(String bzStart) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

        Date myDate = null;
        String bzend = null;
        try {
            myDate = formatter.parse(bzStart);
            Calendar c = Calendar.getInstance();
            c.setTime(myDate);
            c.add(Calendar.MONTH, -1);
            myDate = c.getTime();
            bzend = formatter.format(myDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return bzend;
    }

    /**
     * 插入数据
     *
     * @param tdHzb
     */
    @Transactional
    public void saveTdHzb(TdHzb tdHzb) {
        if (tdHzb.getId() != null) {
            TdHzb result = getTdHzb(tdHzb.getId());
            if (result != null) {
                tdHzbDao.update(tdHzb);
            } else {
                tdHzbDao.insert(tdHzb);
            }
        } else {
            tdHzbDao.insert(tdHzb);
        }
    }

    /**
     * 删除数据
     *
     * @param id
     */
    @Transactional
    public void deleteTdHzb(Integer id) {

        tdHzbDao.delete(id);
    }

    /**
     * 删除数据
     *
     * @param tdHzbList
     */
    @Transactional
    public void deleteTdHzbBatch(List<String> tdHzbList) {
        for (String id : tdHzbList) {
            deleteTdHzb(Integer.valueOf(id));
        }
    }

    /**
     * 根据ID获取数据
     *
     * @param id
     */
    @Transactional
    public TdHzb getTdHzb(Integer id) {

        return tdHzbDao.getTdHzbById(id);
    }

    /**
     * 导出
     *
     * @param
     */
    @Transactional
    public String exportExcel(TdHzbParams tdHzbParams, HttpServletRequest request, HttpServletResponse response) {
        try {
            String clientFileName = encodeFilename(request, System.currentTimeMillis() + "");
            response.reset();
            response.setHeader("Content-Disposition", "attachment; " + clientFileName + ".xls");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream os = response.getOutputStream();
            List dataList = queryTdHzbList(tdHzbParams);
            List nameList = new ArrayList();
            nameList.add("部门");
            nameList.add("姓名");
            nameList.add("启动");
            nameList.add("总天数");
            nameList.add("总时数");
            nameList.add("日均累计");
            nameList.add("预期用时");
            nameList.add("带动家人");
            nameList.add("带动客户");
            nameList.add("本月日均");
            nameList.add("上月日均");
            nameList.add("本月累计天数");
            nameList.add("上月累计天数");
            nameList.add("本月中断天数");
            nameList.add("上月中断天数");
            nameList.add("本月中断天数");
            nameList.add("上月中断天数");
            nameList.add("本月各项均衡");
            nameList.add("上月各项均衡");
            this.exportExcel(nameList, dataList, os);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * @return HSSFWorkbook
     */
    public HSSFWorkbook createWorkbook(List fieldName, List fieldData) {
        List<CodeInfo> vipTypeList = CodeInfoCache.getCodeInfo(CodeType.VIP_TYPE);
        List<CodeInfo> overdueTypeList = CodeInfoCache.getCodeInfo(CodeType.OVERDUE_TYPE);

        // 第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("天道汇总表");
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

        HSSFCellStyle cellstyle = (HSSFCellStyle) wb.createCellStyle();// 设置表头样式
        cellstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 设置垂直居中
        cellstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 设置水平居中
        cellstyle.setWrapText(true); // 设置为自动换行
        HSSFFont cellFont = (HSSFFont) wb.createFont(); // 创建表头字体样式
        cellFont.setFontHeightInPoints((short) 10); // 设置字体大小
        cellFont.setFontName("宋体"); // 设置字体类型
        cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗
        cellstyle.setFont(cellFont); // 为表头样式设置字体样式


        for (int i = 0; i < fieldName.size(); i++) {
            HSSFCell cell = row.createCell((short) i);
            cell.setCellValue((String) fieldName.get(i));
            cell.setCellStyle(cellstyle);
        }

        TdHzb tdHzb = null;

        // 第五步，写入实体数据 实际应用中这些数据从数据库得到，

        for (int i = 0; i < fieldData.size(); i++) {
            row = sheet.createRow(i + 1);
            tdHzb = (TdHzb) fieldData.get(i);
            // 第四步，创建单元格，并设置值

            if (tdHzb.getOrgName() == null) {
                row.createCell((short) 0).setCellValue("");
            } else {
                row.createCell((short) 0).setCellValue(tdHzb.getOrgName());
            }
            if (tdHzb.getUserName() == null) {
                row.createCell((short) 1).setCellValue("");
            } else {
                row.createCell((short) 1).setCellValue(tdHzb.getUserName());
            }
            if (tdHzb.getDateStart() == null) {
                row.createCell((short) 2).setCellValue("");
            } else {
                row.createCell((short) 2).setCellValue(tdHzb.getDateStart());
            }
            if (tdHzb.getZTs() == null) {
                row.createCell((short) 3).setCellValue("");
            } else {
                row.createCell((short) 3).setCellValue(tdHzb.getZTs());
            }
            if (tdHzb.getZSs() == null) {
                row.createCell((short) 4).setCellValue("");
            } else {
                row.createCell((short) 4).setCellValue(tdHzb.getZSs());
            }
            if (tdHzb.getAverageDaily() == null) {
                row.createCell((short) 5).setCellValue("");
            } else {
                row.createCell((short) 5).setCellValue(tdHzb.getAverageDaily());
            }
            if (tdHzb.getExpectedTime() == null) {
                row.createCell((short) 6).setCellValue("");
            } else {
                row.createCell((short) 6).setCellValue(tdHzb.getExpectedTime());
            }
            if (tdHzb.getDriveFamily() == null) {
                row.createCell((short) 7).setCellValue("");
            } else {
                row.createCell((short) 7).setCellValue(tdHzb.getDriveFamily());
            }
            if (tdHzb.getDriveCustomer() == null) {
                row.createCell((short) 8).setCellValue("");
            } else {
                row.createCell((short) 8).setCellValue(tdHzb.getDriveCustomer());
            }
            if (tdHzb.getBRj() == null) {
                row.createCell((short) 9).setCellValue("");
            } else {
                row.createCell((short) 9).setCellValue(tdHzb.getBRj());
            }
            if (tdHzb.getSRj() == null) {
                row.createCell((short) 10).setCellValue("");
            } else {
                row.createCell((short) 10).setCellValue(tdHzb.getSRj());
            }
            if (tdHzb.getBLjts() == null) {
                row.createCell((short) 11).setCellValue("");
            } else {
                row.createCell((short) 11).setCellValue(tdHzb.getBLjts());
            }
            if (tdHzb.getSLjts() == null) {
                row.createCell((short) 12).setCellValue("");
            } else {
                row.createCell((short) 12).setCellValue(tdHzb.getSLjts());
            }
            if (tdHzb.getBZcts() == null) {
                row.createCell((short) 13).setCellValue("");
            } else {
                row.createCell((short) 13).setCellValue(tdHzb.getBZcts());
            }
            if (tdHzb.getSZcts() == null) {
                row.createCell((short) 14).setCellValue("");
            } else {
                row.createCell((short) 14).setCellValue(tdHzb.getSZcts());
            }
            if (tdHzb.getBZdts() == null) {
                row.createCell((short) 15).setCellValue("");
            } else {
                row.createCell((short) 15).setCellValue(tdHzb.getBZdts());
            }
            if (tdHzb.getSZdts() == null) {
                row.createCell((short) 16).setCellValue("");
            } else {
                row.createCell((short) 16).setCellValue(tdHzb.getSZdts());
            }
            if (tdHzb.getBJh() == null) {
                row.createCell((short) 17).setCellValue("");
            } else {
                row.createCell((short) 17).setCellValue(tdHzb.getBJh());
            }
            if (tdHzb.getSJh() == null) {
                row.createCell((short) 18).setCellValue("");
            } else {
                row.createCell((short) 18).setCellValue(tdHzb.getSJh());
            }




        }
        //自适应列宽
        for (int i = 0; i < fieldName.size(); i++) {
            sheet.autoSizeColumn((short) i);
        }


        return wb;
    }


    //将信息写入输出流的方法。
    public void exportExcel(List fieldName, List fieldData, OutputStream os) throws Exception {
        HSSFWorkbook wb = createWorkbook(fieldName, fieldData);
        wb.write(os);
        os.close();
    }
}